// pages/index/examStudent/index.js
const util = require('../../../utils/util'); // 导入 util.js

Page({
  data: {
    examDetail: {},
    questionList: [],
    answers: {}, // 用于存储当前答题模式下的答案
    countdown: 0,
    countdownStr: '',
    isExpired: false,
    timer: null,
    readonly: false, // 是否只读模式
    timerClass: '',
    studentList: [], // 老师端：已提交学生列表
    selectedStudentId: null, // 老师端：当前选中的学生ID
    studentAnswers: {}, // 只读模式下：当前学生（自己或老师选中的）的答题详情
    showStudentList: false, // 老师端：是否显示学生列表
    myScore: 0, // 学生端只读模式：自己的分数
    selectedStudentScore: 0, // 老师端只读模式：选中学生的分数
    formattedExamTime: '' // 新增：用于存储格式化后的考试时间
  },
  onLoad(options) {
    const examId = options.id;
    const readonly = options.readonly == 1;
    this.setData({ readonly });
    const userInfo = wx.getStorageSync('userInfo') || {};
    const user = userInfo.user || userInfo;
    this.setData({
      isTeacher: user.identity == 1
    });
    wx.request({
      url: 'http://localhost:9090/api/exam/detail',
      method: 'GET',
      data: { id: examId },
      success: res => {
        if (res.data.code == 200 || res.data.code == '200') {
          let exam = res.data.data.exam;
          let questions = res.data.data.questions.map(q => {
            if (typeof q.options === 'string') {
              try { q.options = JSON.parse(q.options); } catch (e) { q.options = []; }
            }
            // 推荐后端返回type字段，否则前端这样判断
            if (!q.options || q.options.length === 0) {
              q.type = '填空题';
            } else if (q.options.length === 2 && q.options.includes('对') && q.options.includes('错')) {
              q.type = '判断题';
            } else {
              q.type = '单选题'; // 默认都按单选题处理
            }
            return q;
          });
          console.log('questions:', questions); // 调试用
          
          // 格式化考试时间并更新到 data
          const formattedTime = util.formatTime(new Date(exam.examTime)); // 将时间字符串转为 Date 对象再格式化

          this.setData({
            examDetail: exam,
            questionList: questions,
            formattedExamTime: formattedTime, // 存储格式化后的时间
            // 如果不是只读模式，answers 初始化为空对象，等待用户填写
            // 如果是只读模式，answers 保持为空，使用 studentAnswers 显示已提交答案
            answers: readonly ? {} : {} // 或者可以尝试加载未提交的草稿答案
          });
          if (!readonly) this.initCountdown(exam.examTime, exam.duration);
           // 老师端：加载已提交学生列表   学生端只读模式：加载自己的答题
          if (readonly) {
            if (user.identity == 1) {
              // 老师端：加载已提交学生列表
              this.loadStudentList(examId);
            } else {
              // 学生端只读模式：加载自己的答题
              this.loadMyAnswers(examId, user.id);
            }
          }
        }
      }
    });
  },
  // 新增：加载当前学生自己的答题
  loadMyAnswers(examId, studentId) {
    wx.request({
      url: 'http://localhost:9090/api/exam/submitStatus',
      method: 'GET',
      data: { examId },
      success: res => {
        if (res.data.code == 200 || res.data.code == '200') {
          const answers = res.data.data.answers || [];
          const myAnswers = {};
          let myScore = 0;
          answers.forEach(a => {
            if (a.studentId == studentId) {
              // 找到当前题目的类型
              const q = this.data.questionList.find(q => q.id == a.questionId);
              if (q && q.type === '多选题' && typeof a.answer === 'string') {
                myAnswers[a.questionId] = a.answer ? a.answer.split(',') : [];
              } else {
                myAnswers[a.questionId] = a.answer;
              }
              myScore = a.score || 0;
            }
          });
          this.setData({
            selectedStudentId: studentId,
            studentAnswers: myAnswers,
            myScore: myScore,
            showStudentList: false
          });
        }
      }
    });
  },
   // 新增：加载已提交学生列表
   loadStudentList(examId) {
    wx.request({
      url: 'http://localhost:9090/api/exam/submitStatus',
      method: 'GET',
      data: { examId },
      success: res => {
        if (res.data.code == 200 || res.data.code == '200') {
          // 这里的 answers 是所有提交记录
          const answers = res.data.data.answers || [];
          // 提取学生ID去重
          const studentMap = {};
          answers.forEach(a => {
            if (!studentMap[a.studentId]) {
              studentMap[a.studentId] = { studentId: a.studentId, name: a.studentName };
            }
          });
          this.setData({
            studentList: Object.values(studentMap),
            showStudentList: true
          });
        }
      }
    });
  },
   // 新增：点击学生，加载该学生答题详情
  onSelectStudent(e) {
    const studentId = e.currentTarget.dataset.studentid;
    const examId = this.data.examDetail.id;
    wx.request({
      url: 'http://localhost:9090/api/exam/submitStatus',
      method: 'GET',
      data: { examId },
      success: res => {
        if (res.data.code == 200 || res.data.code == '200') {
          const answers = res.data.data.answers || [];
          // 过滤出该学生的答题
          const studentAnswers = {};
          let studentScore = 0;
          answers.forEach(a => {
            if (a.studentId == studentId) {
              const q = this.data.questionList.find(q => q.id == a.questionId);
              if (q && q.type == '多选题' && typeof a.answer === 'string') {
                studentAnswers[a.questionId] = a.answer ? a.answer.split(',') : [];
              } else {
                studentAnswers[a.questionId] = a.answer; // 修正这里
              }
              studentScore = a.score || 0;
            }
          });
          console.log(studentAnswers,'studentAnswers');
          this.setData({
            selectedStudentId: studentId,
            studentAnswers,
            selectedStudentScore: studentScore,
            showStudentList: false
          });
        }
      }
    });
  },
   // 新增：返回学生列表
   backToStudentList() {
    this.setData({
      showStudentList: true,
      selectedStudentId: null,
      studentAnswers: {}
    });
  },
  initCountdown(examTime, duration) {
    // examTime为考试开始时间，duration为分钟数
    const start = new Date(examTime).getTime();
    const end = start + (duration || 60) * 60 * 1000;
    const now = Date.now();
    let left = Math.floor((end - now) / 1000);
    if (left <= 0) {
      this.setData({ countdown: 0, countdownStr: '已截止', isExpired: true, timerClass: 'expired' });
      return;
    }
    this.setData({ countdown: left, isExpired: false, timerClass: '' });
    this.updateCountdownStr(left);
    this.data.timer = setInterval(() => {
      left--;
      if (left <= 0) {
        clearInterval(this.data.timer);
        this.setData({ countdown: 0, countdownStr: '已截止', isExpired: true, timerClass: 'expired' });
      } else {
        this.updateCountdownStr(left);
      }
    }, 1000);
  },
  updateCountdownStr(left) {
    let m = Math.floor(left / 60);
    let s = left % 60;
    this.setData({ countdownStr: `${m}分${s}秒` });
    if (left < 60) this.setData({ timerClass: 'urgent' });
  },
  onUnload() {
    if (this.data.timer) clearInterval(this.data.timer);
  },
  // 处理单选/判断题选择变化
  onAnswerChange(e) {
    const qid = String(e.currentTarget.dataset.qid); // 确保 qid 是字符串，与 answers 的 key 类型一致
    const value = e.detail.value; // radio-group 的 value 直接就是选中的字符串
    console.log('onAnswerChange event:', e);
    console.log('qid:', qid, 'value:', value);
    this.setData({
      [`answers.${qid}`]: value
    });
  },
  // 处理填空题输入
  onFillInInput(e) {
    const qid = String(e.currentTarget.dataset.qid);
    const value = e.detail.value;
    console.log('onFillInInput event:', e);
    console.log('qid:', qid, 'value:', value);
    this.setData({
      [`answers.${qid}`]: value
    });
  },
  // 处理多选题选择变化
  onCheckboxChange(e) {
    const qid = String(e.currentTarget.dataset.qid);
    const values = e.detail.value; // 多选框返回的是一个数组
    console.log('onCheckboxChange event:', e);
    console.log('qid:', qid, 'values:', values);
    this.setData({
      [`answers.${qid}`]: values
    });
  },
  submitAnswer() {
    
    if (this.data.isExpired) {
      wx.showToast({ title: '已截止，无法提交', icon: 'none' });
      return;
    }
    // 检查所有题目是否已回答
    let allAnswered = this.data.questionList.every(q => {
      const answer = this.data.answers[String(q.id)];
      if (q.type === '填空题' || q.type === '单选题' || q.type === '判断题') {
        return answer !== undefined && answer !== null && answer !== '';
      } else if (q.type === '多选题') {
        return answer !== undefined && answer !== null && Array.isArray(answer) && answer.length > 0;
      }
      // 对于未知类型，默认认为未回答
      return false;
    });

    if (!allAnswered) {
      wx.showToast({ title: '请完成所有题目', icon: 'none' });
      return;
    }

    const userInfo = wx.getStorageSync('userInfo') || {};
    const user = userInfo.user || userInfo;
    const examId = this.data.examDetail.id;
    const answers = this.data.answers;
    const questionList = this.data.questionList;
  
    // 构造提交数据
    const answerArr = questionList.map(q => {
      let ans = answers[q.id];
      // 多选题需要转成英文逗号分隔字符串
      if (q.type === '多选题' && Array.isArray(ans)) {
        ans = ans.join(',');
      }
      // 其它题型直接用字符串（未答题时为undefined/null，建议转空字符串）
      return {
        questionId: q.id,
        answer: ans || ''
      };
    });
    // const user = wx.getStorageSync('userInfo').user || {};
    wx.request({
      url: 'http://localhost:9090/api/exam/submit',
      method: 'POST',
      header: { 'content-type': 'application/json' },
      data: {
        examId: examId,
        studentId: user.id,
        answers: answerArr
      },
      success: res => {
        if (res.data.code == 200 || res.data.code == '200') {
          wx.showToast({ title: '提交成功', icon: 'success' });
          // 设置刷新标志
          wx.setStorageSync('refreshExamList', true);
          wx.navigateBack();
        } else {
          wx.showToast({ title: '提交失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '提交失败', icon: 'none' });
      }
    });
  }
});